package com.sxf.rental.utils;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {
    public static final String SECRET_KEY="sxf";

    public static final Long EXPIRATION_TIME=1000L*60*30;

    public  static String createToken(Map<String,Object> payload){
        DateTime now=DateTime.now();
        DateTime newTime=new DateTime(now.getTime()+EXPIRATION_TIME);
        //设置签发时间
        payload.put(JWTPayload.ISSUED_AT,now);
        //设置过期时间
        payload.put(JWTPayload.EXPIRES_AT,newTime);
        //设置生效时间,确保ToKen在签发后立即生效
        payload.put(JWTPayload.NOT_BEFORE,now);

        return JWTUtil.createToken(payload,SECRET_KEY.getBytes());
    }

    public static JWTPayload parseToken(String token){
        JWT jwt = JWTUtil.parseToken(token);
        if (!jwt.setKey(SECRET_KEY.getBytes()).verify()){
            throw new RuntimeException("ToKen异常");
        }
        if (!jwt.validate(0)){
            throw new RuntimeException("ToKen已过期");
        }
        return jwt.getPayload();
    }

}
